/*
 * Created by guoyh on Sun Dec 11 2022 21:45:49
 * leetcode NO.19 https://leetcode.cn/problems/remove-nth-node-from-end-of-list/  
 */

#include <iostream>
#include <gtest/gtest.h>
using namespace std;

 struct ListNode {
     int val;
     ListNode *next;
     ListNode() : val(0), next(nullptr) {}
     ListNode(int x) : val(x), next(nullptr) {}
     ListNode(int x, ListNode *next) : val(x), next(next) {}
 };

class Solution {
public:
    ListNode* removeNthFromEnd(ListNode* head, int n) {
        if(head && !head->next && n == 1) return nullptr;
        int size = 0;
        ListNode* p = head;
        while(p){
            size++;
            p = p->next;
        }
        p = head;
        // ListNode* successor = p->next;
        // pos: 将被删除的节点的前驱节点位置，从1开始算
        int pos = size - n;
        if(pos == 0){
            // 将删除的是第一个节点
            ListNode* newHead = head->next;
            head->next = nullptr;
            return newHead;
        }
        int c = 1;
        while(c < pos){
            c++;
            p = p->next;
            // successor = successor->next;
        }
        p->next = p->next->next; 

        return head;
    }
};

int add(int a, int b) {
    return a + b;
}

// 尾插法创建链表
ListNode* build_linklist(vector<int> v){
    ListNode* dummy = new ListNode();
    ListNode* tail = dummy;
    for(int i : v){
        ListNode* newNode = new ListNode(i);
        newNode->next = nullptr;
        tail->next = newNode;
        tail = tail->next;
    }
    return dummy->next;
}


void print(ListNode* l){
    while(l){
        cout<<l->val<<",";
        l = l->next;
    }
    cout<<endl;
}

TEST(MyTest, AddTest) {
    vector<int> v = {1,2,3,4,5};
    ListNode* l = build_linklist(v);
    Solution slu;
    ListNode* res = slu.removeNthFromEnd(l, 2);
    print(res);

    EXPECT_NE(res, nullptr);
}

int main(int argc, char *argv[]) {
    ::testing::InitGoogleTest(&argc, argv);
    return RUN_ALL_TESTS();
}
